package com.firewolf.realms;

import com.firewolf.beans.User;
import com.firewolf.service.UserService;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 作者：刘兴
 * 时间:18/12/3
 **/
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService service;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String username = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roles = service.findRolesByName(username);
        Set<String> permissions = service.findPermissionByName(username);
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        System.out.println(ReflectionToStringBuilder.toString(roles));
        System.out.println(ReflectionToStringBuilder.toString(permissions));
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        User user =  service.findUserByName(userName);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),getName());
        info.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
        return info;
    }

    public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("1234","1111",1024);
        System.out.println(md5Hash);
    }

}
